package com.sjtu.bookread.Fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.sjtu.bookread.BookDetailActivity;
import com.sjtu.bookread.R;
import com.sjtu.bookread.myRecyclerview.CateRecyclerViewAdapter;
import com.sjtu.bookread.obj.AllRankingObj;
import com.sjtu.bookread.obj.BookListObj;
import com.sjtu.bookread.obj.BookObj;
import com.sjtu.bookread.obj.BookObj1;
import com.sjtu.bookread.obj.SingleRankingObj;
import com.sjtu.bookread.service.BookService;
import com.sjtu.bookread.service.RecomService;

import java.util.ArrayList;
import java.util.List;

public class RankingFragment1 extends Fragment {
    private RecyclerView recyclerView;
    private ProgressBar progressBar;
    private SwipeRefreshLayout swipeRefreshLayout;
    private List<BookObj1> bookObjList = new ArrayList<>();
    private CateRecyclerViewAdapter recyclerViewAdapter;

    private int total;                  //书籍总数
    private int lastVisibleItem = 0;
    private final int PAGE_COUNT = 10;

    private String rankingid = "";

    Handler handler = new Handler();
    RecomService recomService = RecomService.getRecomService();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initBookList();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_detail_category, null);

        progressBar = view.findViewById(R.id.detail_category_progressBar);
        swipeRefreshLayout = view.findViewById(R.id.detail_category_swipeRefresh);

        //设置RecyclerView
        recyclerView = view.findViewById(R.id.detail_category_recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerViewAdapter = new CateRecyclerViewAdapter(getBookList(0, PAGE_COUNT), getActivity(), getBookList(0, PAGE_COUNT).size() > 0 ? true : false, true);
        recyclerViewAdapter.setOnItemClickListener(new CateRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position) {
                //跳转到书籍详情界面
                Intent intent = new Intent(getActivity(), BookDetailActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("bookobj", bookObjList.get(position));
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
        recyclerView.setAdapter(recyclerViewAdapter);

        //设置下拉显示的动画颜色
        swipeRefreshLayout.setColorSchemeColors(Color.RED, Color.BLUE);
        //下拉刷新的回调事件
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //数据刷新
                initBookList();
            }
        });

        //设置滑动监听器
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                // 在newState为滑到底部时
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    // 如果没有隐藏footView，那么最后一个条目的位置就比我们的getItemCount少1
                    if (recyclerViewAdapter.isFadeTips() == false && lastVisibleItem + 1 == recyclerViewAdapter.getItemCount()) {
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                // 然后调用updateRecyclerview方法更新RecyclerView
                                updateRecyclerView(recyclerViewAdapter.getLastPosition(), recyclerViewAdapter.getLastPosition() + PAGE_COUNT);
                            }
                        }, 500);
                    }

                    // 如果隐藏了提示条，我们又上拉加载时，那么最后一个条目就要比getItemCount要少2
                    if (recyclerViewAdapter.isFadeTips() == true && lastVisibleItem + 2 == recyclerViewAdapter.getItemCount()) {
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                // 然后调用updateRecyclerview方法更新RecyclerView
                                updateRecyclerView(recyclerViewAdapter.getLastPosition(), recyclerViewAdapter.getLastPosition() + PAGE_COUNT);
                            }
                        }, 500);
                    }
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                // 在滑动完成后，拿到最后一个可见的item的位置
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });

        return view;
    }

    List<BookObj1> getBookList(int from, int to) {
        List<BookObj1> newList = new ArrayList<>();
        for (int i = from; i < to && i < bookObjList.size(); ++i) {
            newList.add(bookObjList.get(i));
        }
        return newList;
    }

    private void updateRecyclerView(int fromIndex, int toIndex) {
        List<BookObj1> newDatas = getBookList(fromIndex, toIndex);
        if (newDatas.size() > 0) {
            recyclerViewAdapter.updateList(newDatas, true);
        } else {
            recyclerViewAdapter.updateList(null, false);
        }
    }

    void initBookList() {
        bookObjList.clear();
        //检查网络连接
        ConnectivityManager connect = (ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connect.getActiveNetworkInfo();
        if (info == null || !info.isAvailable()) {
            Toast.makeText(getActivity(), "网络连接状况：未连接", Toast.LENGTH_LONG).show();
            return;
        }


        new Thread(new Runnable() {
            @Override
            public void run() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        BookListObj bookListObj= recomService.getRankingBookList();
                        if (bookListObj == null || !bookListObj.isOk()) {
                            Looper.prepare();
                            Toast.makeText(getContext(), "获取失败", Toast.LENGTH_LONG).show();
                            Looper.loop();
                            Log.d("error", "获取单一排行榜失败");
                            return;
                        }
                        List<BookObj1> objList = bookListObj.getBooks();
                        total = bookListObj.getTotal();
                        for (int i = 0; i < objList.size(); ++i) {
                            BookObj1 bookObj = objList.get(i);
                            String intro = bookObj.getShortIntro();
                            bookObj.setShortIntro(intro);
                            bookObjList.add(bookObj);
                        }
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                updateRecyclerView(0, PAGE_COUNT);
                                progressBar.setVisibility(View.GONE);
                                //数据加载完毕时取消动画
                                swipeRefreshLayout.setRefreshing(false);
                                // Toast.makeText(getActivity(), "数据刷新完成", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }).start();
            }
        }).start();
    }
}
